package com.yuyou.fn.interceptor;

import com.yuyou.fn.platform.vo.AccessTokenVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Created by wens on 16-12-14.
 */
public class LogInterceptor extends HandlerInterceptorAdapter {

    private final Logger logger = LoggerFactory.getLogger(LogInterceptor.class);

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        AccessTokenVo accessToken = (AccessTokenVo)request.getAttribute("accessToken");
        logger.info("uri:{},optUserId:{},params:[{}]", request.getRequestURI() ,accessToken == null ? "" : accessToken.getUserId() , requestParams(request) );
    }

    private String requestParams(HttpServletRequest request) {
        Map parameterMap = request.getParameterMap();
        List<String>  params = new ArrayList<>(parameterMap.size());
        for(Object key  : parameterMap.keySet() ){
            StringBuilder sb  = new StringBuilder(10) ;
            Object o = parameterMap.get(key);
            sb.append(key).append("=").append(o.getClass().isArray() ? Arrays.toString((Object[]) o) : o );
            params.add(sb.toString());
        }
        return StringUtils.join(params,",") ;
    }
}
